package ce.com.cenewbluesdk.uitl;

/**
 * Created by Administrator on 2016/11/22.
 * 专门解析字节数组的类
 * 内部维护了offset, {@link #readInt(int)}时要注意顺序...
 */

public class ByteParser {
    private byte[] data;
    private int offset;

    public ByteParser(byte[] data) {
        this(data, 0);
    }

    public ByteParser(byte[] data, int offset) {
        this.data = data;
        this.offset = offset;
    }

    public int getOffset() {
        return offset;
    }

    public void setOffset(int offset) {
        this.offset = offset;
    }

    public void addOffset(int length) {
        this.offset += length;
    }

    /**
     * int的范围为[-2147483648, 2147483647], 正数部分用来表示时间约可以表示到2038/1/19
     * @param length
     * @return
     */
    public int readInt(int length) {
        if (length < 1 && length > 4) {
            throw new RuntimeException("length取值只可为1, 2, 3, 4, length=" + length);
        }
        int value = 0;
        for (int i = 0; i < length; i++) {
            value += (data[offset + i] & 0xff) << (8 * i);// 按位取反>乘除>加减>移位>关系>&>^>|>逻辑
        }
        addOffset(length);
        return value;
    }

    public byte[] readBytes(int length) {
        byte[] bytes = new byte[length];
        System.arraycopy(data, offset, bytes, 0, length);
        addOffset(length);
        return bytes;
    }

    public String readString(int length) {
        String str = new String(data, offset, length);
        // TODO: 2015/11/25 是否要处理末尾的\u0000?
        addOffset(length);
        return str;
    }
}
